package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.ReportApi;
import com.tanhua.dubbo.server.pojo.Report;
import com.tanhua.server.mapper.ReportTxtMapper;
import com.tanhua.server.pojo.*;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TestSoulService {

    @Autowired
    private QuestionaireService questionaireService;

    @Autowired
    private QuestionsService questionsService;

    @Autowired
    private OptionsService optionsService;

    @Reference(version = "1.0.0")
    private ReportApi reportApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private ReportTxtMapper reportTxtMapper;

    @Value("${tanhua.sso.default.recommend.users}")
    private String recommendUsers;

    /**
     * 测灵魂-问卷列表
     *
     * @return
     */
    public List<QuestionaireVo> queryQuestionaireList() {
        //获取当前用户信息
        User user = UserThreadLocal.get();

        //查询mongodb中是否存在报告表,如果没有就初始化生成对应的报告表
        //查询数据库,获取三张问卷表信息
        List<Questionaire> questionaireList = questionaireService.queryQuestionaireList();

        //创建返回前端的Vo集合
        List<QuestionaireVo> questionaireVoList = new ArrayList<>();
        //查询题目列表并封装对应的选项
        for (Questionaire questionaire : questionaireList) {

            QuestionaireVo questionaireVo = new QuestionaireVo();
            questionaireVo.setId(questionaire.getId());  //问卷id
            questionaireVo.setCover(questionaire.getCover()); //问卷封面
            questionaireVo.setStar(questionaire.getStar()); //问卷星别
            questionaireVo.setLevel(questionaire.getLevel());//问卷级别
            questionaireVo.setName(questionaire.getName()); //问卷名称

            //根据星别查询对应的问题
            List<Questions> questionsList = questionsService.queryQuentionsByStar(questionaire.getStar());
            questionaireVo.setQuestions(questionsList); //问题

            //根据用户id和星别查询报告表,获取报告的对象
            Report scoreByStar = reportApi.findScoreByStar(user.getId(), questionaire.getStar());

            if (null == scoreByStar) {
                //生成初始的报告表
                reportApi.saveReportList(user.getId(), questionaire.getStar(), 0);
                //如果星别为2,就解锁
                if (questionaireVo.getStar() == 2) {
                    questionaireVo.setIsLock(0);
                } else {//否则锁住
                    questionaireVo.setIsLock(1);
                }

            }

            //非空
            if (scoreByStar != null) {
                questionaireVo.setIsLock(scoreByStar.getIsLock());  //是否锁住
                if (scoreByStar.getScore() > 0) {
                    questionaireVo.setReportId(scoreByStar.getId().toHexString()); //报告id
                }
            }


            questionaireVoList.add(questionaireVo);

        }
        return questionaireVoList;
    }

    /**
     * 提交问卷
     *
     * @param answersList
     * @return
     */
    public String saveQuestionList(List<Answers> answersList) {
        //获取当前用户信息
        User user = UserThreadLocal.get();

        int score = 0;
        //获取总分
        for (Answers answers : answersList) {
            String optionId = answers.getOptionId();
            Options options = optionsService.queryById(optionId);
            score += options.getScore();
        }

        String reportId = null;
        //获取题目对应的星别
        for (Answers answers : answersList) {
            //获取问题id
            String questionId = answers.getQuestionId();
            //根据问题id找到对应的问题
            Questions questions = questionsService.queryById(questionId);
            //获取当前的星级
            Integer star = questions.getStar();
            //将总分添加到报告表中
            reportId = reportApi.saveReportList(user.getId(), star, score);
            break;
        }


        return reportId;
    }

    /**
     * 测灵魂-查看结果
     *
     * @param reportId 报告id
     * @return
     */
    public TestSoulResultVo queryQuestionResult(String reportId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();

        //创建对象
        TestSoulResultVo testSoulResultVo = new TestSoulResultVo();
        //调用方法查询当前用户分数
        Report report2 = this.reportApi.queryReportOne(reportId);
        //当前用户成绩
        int score = report2.getScore();//todo
        //若当前用户分数为null
        if (score == 0) {
            //当前用户未进行过测试
            return testSoulResultVo;
        }
        //确定鉴定结果和鉴定图片
        QueryWrapper<ReportTxt> wrapper = new QueryWrapper<>();
        if (score <= 21) {
            wrapper.eq("id", 1);
        } else if (score <= 40) {
            wrapper.eq("id", 2);
        } else if (score <= 55) {
            wrapper.eq("id", 3);
        } else {
            wrapper.eq("id", 4);
        }
        ReportTxt reportTxt = reportTxtMapper.selectOne(wrapper);
        //鉴定结果和鉴定图片
        testSoulResultVo.setConclusion(reportTxt.getConclusion());
        testSoulResultVo.setCover(reportTxt.getCover());
        //随机维度
        List<DimensionsVo> list1 = new ArrayList<>();
        String dimStr = "60%,70%,80%,90%";
        list1.add(new DimensionsVo("外向", null));
        list1.add(new DimensionsVo("判断", null));
        list1.add(new DimensionsVo("抽象", null));
        list1.add(new DimensionsVo("理性", null));

        String[] split = StringUtils.split(dimStr, ",");
        for (DimensionsVo s : list1) {
            for (int i = 0; i < split.length; i++) {
                s.setValue(split[RandomUtils.nextInt(0, 3)]);
                break;
            }
        }
        testSoulResultVo.setDimensions(list1);

        //根据报告id查询对应的报告
        Report report = reportApi.queryReportOne(reportId);
        //根据获取的报告星级查询获取相似的用户报告
        List<Report> reportList = reportApi.queryRecommendReprt(report.getStar());

        ArrayList<SimilarYou> similarYous = new ArrayList<>();
        //再根据报告的id集合查询用户对应的信息
        for (Report report1 : reportList) {

            if (report1.getUserId()==user.getId()){
                continue;
            }
            //匹配用户的成绩
            Integer score1 = report1.getScore();
            //条件：成绩相似
            if (Math.abs(score - score1) < 5) {
                //根据用户id查询用户的详细信息
                UserInfo userInfo = this.userInfoService.queryById(report1.getUserId());
                //相似对象
                SimilarYou similarYou = new SimilarYou();
                similarYou.setId(Math.toIntExact(report1.getUserId()));
                similarYou.setAvatar(userInfo.getLogo());
                //添加到SimilarYou对象集合
                similarYous.add(similarYou);
            }
        }
        //相似用户列表长度小于10，填充默认推荐用户
        if (similarYous.size() < 10) {
            //所有的推荐用户id列表
            String[] recommendUserIds = this.recommendUsers.split(",");
            for (int i = 0; i < recommendUserIds.length; i++) {
                String recommendUserId = recommendUserIds[i];
                //如果推荐的id与当前用户id不相同进行添加
                if (Long.valueOf(recommendUserId) != user.getId()) {
                    SimilarYou similarYou = new SimilarYou();
                    //默认推荐用户
                    similarYou.setId(Integer.valueOf(recommendUserId));
                    //调用方法查询推荐用户头像
                    String avatar = this.userInfoService.queryById(Long.valueOf(recommendUserId)).getLogo();
                    similarYou.setAvatar(avatar);
                    //添加到SimilarYou对象集合
                    similarYous.add(similarYou);
                }
            }
        }
        testSoulResultVo.setSimilarYou(similarYous);
        return testSoulResultVo;
    }
}